package com.focusai.efairy.ui.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.focusai.efairy.R;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.exception.ServerException;
import com.focusai.efairy.ui.activity.global.ReloginDialogActivity;
import com.focusai.efairy.ui.widget.WaitingDialog;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.ErrorCodeUtils;
import com.focusai.efairy.utils.log.Log;

/**
 * BaseFragment
 */
public abstract class BaseFragment extends Fragment {

    private static final String TAG = "YS.BaseFragment";

    // --------------------------------------------------------------------
    // ------------------------- Common message code ----------------------

    // --------------------------------------------------------------------

    protected Context mContext;

    private Toast mToast;

    /**
     * 界面更新相关操作消息处理handler
     */
    private Handler mUiHandler;

    /**
     * 耗时操作需在此handler处理
     */
    private Handler mProcHandler;

    /**
     * 子线程
     */
    private HandlerThread mProcThread;

    private WaitingDialog waitingDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.D(TAG, "onCreate");
        mContext = getActivity();

        if (useHandleThread()) {
            mProcThread = new HandlerThread(this.getClass().getName());
            // mProcThread.setPriority(Thread.MIN_PRIORITY); //设置线程优先级
            mProcThread.start();

            mUiHandler = new Handler(getActivity().getMainLooper(), new Handler.Callback() {

                @Override
                public boolean handleMessage(Message msg) {
                    return uiHandlerCallback(msg);
                }
            });

            mProcHandler = new Handler(mProcThread.getLooper(), new Handler.Callback() {

                @Override
                public boolean handleMessage(Message msg) {
                    return procHandlerCallback(msg);
                }
            });
        }

    }

    /**
     * 需要在ui线程执行
     *
     * @return
     */
    protected WaitingDialog getSingleDialog() {
        if (waitingDialog == null) {
            waitingDialog = new WaitingDialog(getActivity());
        }
        return this.waitingDialog;
    }

    protected void showSingleDialog(final String msg) {
        if (getUiHandler() != null){
            getUiHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (waitingDialog == null) {
                        waitingDialog = new WaitingDialog(getActivity());
                    }
                    waitingDialog.setMessage(msg);
                    waitingDialog.show();
                }
            });
        }else {
            if (waitingDialog == null) {
                waitingDialog = new WaitingDialog(getActivity());
            }
            waitingDialog.setMessage(msg);
            waitingDialog.show();
        }
    }

    /**
     * 一个不能被取消的Dialog
     *
     * @param msg 显示的信息
     */
    protected void showNotCancelableDialog(String msg) {
        Dialog dialog = getSingleDialog();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        showSingleDialog(msg);
    }

    protected void closeSingleDialog() {
        if (waitingDialog != null && (waitingDialog.isShowing())) {
            getUiHandler().post(new Runnable() {
                @Override
                public void run() {
                    waitingDialog.cancel();
                }
            });
        }
    }

    protected boolean useHandleThread() {
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onDestroy() {
        if (mProcThread != null) {
            mProcThread.quit();
            mProcThread = null;
        }

        super.onDestroy();
    }

    /**
     * 是否为根入口
     *
     * @return
     */
    protected boolean isRootActivity() {
        return false;
    }

    public Context getContext() {
        return mContext;
    }

    public Handler getUiHandler() {
        return mUiHandler;
    }

    public Handler getProcHandler() {
        return mProcHandler;
    }


    /**
     * UI更新请求消息处理函数
     * <p/>
     * 子类可重载此函数，已处理自己的私有消息
     *
     * @param msg
     * @return
     */
    protected boolean uiHandlerCallback(Message msg) {
        return false;
    }

    /**
     * 与界面无关的操作消息处理函数
     * <p/>
     * 子类可重载此函数，已处理自己的私有消息
     *
     * @param msg
     * @return
     */
    protected boolean procHandlerCallback(Message msg) {
        return false;
    }

    /**
     * Init view.
     */
    protected void initView(View view) {

    }

    /**
     * Set default value to target view, or other object.
     */
    protected void setDefaultValues() {

    }

    /**
     * Bind events to target view.
     */
    protected void bindEvents() {

    }

    public void showToast(String info) {
        if (getActivity() == null) {
            return;
        }

        if (mToast == null) {
            mToast = Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT);

            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

            mToast.setGravity(Gravity.TOP, 0, dm.heightPixels / 5);
        } else {
            mToast.setText(info);
        }
        mToast.show();
    }

    public void showToast(int resId) {
        if (getActivity() == null) {
            return;
        }

        if (mToast == null) {
            mToast = Toast.makeText(getActivity(), resId, Toast.LENGTH_SHORT);

            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

            mToast.setGravity(Gravity.TOP, 0, dm.heightPixels / 5);
        } else {
            mToast.setText(resId);
        }
        mToast.show();
    }

    public void showToastOnUiThread(final int resId) {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showToast(resId);
            }
        });
    }

    public void showToastOnUiThread(final String info) {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showToast(info);
            }
        });
    }

    // --------------- Normal Functions End ---------------------------------

    public <T extends View> T findView(View container, int id) {
        return (T) container.findViewById(id);
    }

    public void doException(Exception exception) {
        doException(exception, true);
    }

    public void doException(Exception exception, boolean show) {
        if (exception != null) {
            if (exception instanceof ServerException) {
                String errorMessage = ((ServerException) exception).getErrorMessage();
                if (ErrorCodeUtils.needReLogin(((ServerException) exception).getErrorCode())){ //是否需要重新登录
                    doLoginOnOther(errorMessage);
                }else {
                    showToastOnUiThread(errorMessage);
                }
            } else if (exception instanceof NetworkException) {
                showToastOnUiThread(((NetworkException) exception).getErrorMessage());
            }
        } else if (show) {
            showToastOnUiThread(R.string.error_network);
        }
    }
    protected void doLoginOnOther(String msg){
        Intent intent = new Intent(mContext, ReloginDialogActivity.class);
        intent.putExtra(Constants.RE_LOGIN_TIME, 0);
        intent.putExtra(Constants.RE_LOGIN_MSG, msg);
        mContext.startActivity(intent);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_right);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getActivity().getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
